from urllib import request
from PIL import Image
import pytesseract
import platform
import os
from com.wzh.mile.unit_test.common.webdriver_single import WebDriverSingle


def is_windows():
    return platform.system() == 'Windows'


def get_path_prefix():
    default_path = 'c:'
    if platform.system() != 'Windows':
        default_path = os.environ['HOME']
    return default_path


def parse_from_url(image_url,save_prefix=get_path_prefix()):
    file_path = save_prefix + '/capture_from_url.png'
    with open(file_path, 'wb') as f:
        u = request.urlopen(image_url)
        f.write(u.read())
    return parse_from_file(file_path)


def parse_from_file(file_path):
    img = Image.open(file_path)
    gray = img.convert('L')
    result_word = None
    if is_windows():
        tessdata_dir_config = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
        pytesseract.pytesseract.tesseract_cmd = "C:\\Program Files (x86)\\Tesseract-OCR\\tesseract"
        result_word = pytesseract.image_to_string(gray, config=tessdata_dir_config)
    else:
        result_word = pytesseract.image_to_string(gray)
    return result_word


def get_capture(web_driver, img_element,save_prefix=get_path_prefix()):
    # 截取当前网页，该网页有我们需要的验证码
    screen_shot_path = save_prefix+'/browser-screen.png'
    capture_area_path = save_prefix+ '/capture-area.png'
    print('截图存放路径：%s' % screen_shot_path)
    print('验证码截图存放路径：%s' % capture_area_path)
    web_driver.save_screenshot(screen_shot_path)
    #img_element 是定位到的验证码
    location = img_element.location  # 获取验证码x,y轴坐标
    size = img_element.size  # 获取验证码的长宽
    rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']),
              int(location['y'] + size['height']))  # 写成我们需要截取的位置坐标
    i = Image.open(screen_shot_path)  # 打开截图
    frame4 = i.crop(rangle)  # 使用Image的crop函数，从截图中再次截取我们需要的区域
    frame4.save(capture_area_path)
    result_word = parse_from_file(capture_area_path)
    print('得到的验证码结果是：%s' % result_word)
    return result_word.replace(' ','')


if __name__ == '__main__':
    driver = WebDriverSingle.get_driver()
    driver.get("https://m.toumile.com/goshortregister.htm")
    driver.find_element_by_id('username').send_keys('13262227170')
    driver.find_element_by_id('password').send_keys('abcd@1234')
    image = driver.find_element_by_id('checkcode_img')  # 定位验证码

    word = get_capture(driver, image)
    driver.find_element_by_id('checkcode').send_keys(word)
    btn = driver.find_element_by_id('JS-regpanel')
    btn.click()
    print('Done')
